package com.jfireframework.commonloggersolution;

import com.jfireframework.baseutil.reflect.UNSAFE;

public class WriteLock
{
    private volatile    Thread owner;
    public static final int    IDLE         = 0;
    public static final int    BUSY         = 1;
    private volatile    int    state        = IDLE;
    private final       long   state_offset = UNSAFE.getFieldOffset("state", WriteLock.class);

    public boolean lock()
    {
        if ((state == IDLE && UNSAFE.compareAndSwapInt(this, state_offset, IDLE, BUSY)))
        {
            owner = Thread.currentThread();
            return true;
        }
        else
        {
            return false;
        }
    }

    public boolean check()
    {
        return owner == Thread.currentThread();
    }

    public void release()
    {
        owner = null;
        state = IDLE;
    }
}
